IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_PageRevisionSave]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_PageRevisionSave]
GO
create procedure [dbo].[cms_sp_PageRevisionSave]
@EntityId int,
@EntityTypeParameter nvarchar(400),
@PageControlTypeParameter nvarchar(400),
@IsLatestRevision bit = null,
@IsLatestCompletedRevision bit = null,
@WorkflowId uniqueidentifier = null
as
declare @CurrentLatestRevisionStatus bit
declare @CurrentLatestCompletedRevisionStatus bit
declare @PublicEntityId int
select 
	@CurrentLatestRevisionStatus = isnull(@IsLatestRevision, IsLatestRevision),
	@CurrentLatestCompletedRevisionStatus = isnull(@IsLatestCompletedRevision, IsLatestCompletedRevision),
	@PublicEntityId = PublicEntityId
from dbo.EntityRevisions
where EntityId = @EntityId and 
	EntityTypeParameter = @EntityTypeParameter
if (@IsLatestRevision is not null) and (@IsLatestRevision = 1)
begin
	update dbo.EntityRevisions
		set IsLatestRevision = 0
	where PublicEntityId = @PublicEntityId and 
		EntityTypeParameter = @EntityTypeParameter
end
if (@IsLatestCompletedRevision is not null) and (@IsLatestCompletedRevision = 1)
begin
	update dbo.EntityRevisions
		set IsLatestCompletedRevision = 0
	where PublicEntityId = @PublicEntityId and 
		EntityTypeParameter = @EntityTypeParameter
end
update dbo.EntityRevisions
set IsLatestRevision = @CurrentLatestRevisionStatus,
	IsLatestCompletedRevision = @CurrentLatestCompletedRevisionStatus,
	IsPublished = @CurrentLatestCompletedRevisionStatus,
	WorkflowId = @WorkflowId
where EntityId = @EntityId and 
	EntityTypeParameter = @EntityTypeParameter
update dbo.EntityRevisions
set IsLatestRevision = @CurrentLatestRevisionStatus,
	IsLatestCompletedRevision = @CurrentLatestCompletedRevisionStatus,
	IsPublished = @CurrentLatestCompletedRevisionStatus
where EntityId in
	(select 
		EntityRevisions.EntityId
	from dbo.EntityRevisions
	inner join dbo.PageControls
		on PageControls.PageControlId = EntityRevisions.EntityId and EntityRevisions.EntityTypeParameter = @PageControlTypeParameter
	where PageId = @EntityId)  and 
	EntityTypeParameter = @PageControlTypeParameter


GO

